package com.remotephone.myapplication

import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.Image
import android.media.ImageReader
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.*
import android.util.Log
import androidx.core.app.NotificationCompat
import java.io.File
import java.io.FileOutputStream

class ScreenshotService : Service() {
    
    private var mediaProjection: MediaProjection? = null
    private var virtualDisplay: VirtualDisplay? = null
    private var imageReader: ImageReader? = null
    private var resultCode: Int = 0
    private var resultData: Intent? = null
    
    private val binder = ScreenshotBinder()
    
    // 回调接口定义在类外部
    interface ScreenshotCallback {
        fun onScreenshotTaken(path: String?)
    }
    
    companion object {
        private const val TAG = "ScreenshotService"
        private const val NOTIFICATION_ID = 2
        private const val CHANNEL_ID = "screenshot_service_channel"
        
        const val ACTION_START_PROJECTION = "START_PROJECTION"
        const val ACTION_TAKE_SCREENSHOT = "TAKE_SCREENSHOT"
        const val ACTION_STOP_PROJECTION = "STOP_PROJECTION"
        
        const val EXTRA_RESULT_CODE = "result_code"
        const val EXTRA_RESULT_DATA = "result_data"
        
        private var callback: ScreenshotCallback? = null
        
        fun setCallback(cb: ScreenshotCallback?) {
            callback = cb
        }
    }
    
    inner class ScreenshotBinder : Binder() {
        fun getService(): ScreenshotService = this@ScreenshotService
    }
    
    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
    }
    
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startForeground(NOTIFICATION_ID, createNotification())
        
        when (intent?.action) {
            ACTION_START_PROJECTION -> {
                resultCode = intent.getIntExtra(EXTRA_RESULT_CODE, Activity.RESULT_CANCELED)
                resultData = intent.getParcelableExtra(EXTRA_RESULT_DATA)
                startMediaProjection()
            }
            ACTION_TAKE_SCREENSHOT -> {
                takeScreenshot()
            }
            ACTION_STOP_PROJECTION -> {
                stopMediaProjection()
                stopSelf()
            }
        }
        
        return START_STICKY
    }
    
    override fun onBind(intent: Intent?): IBinder = binder
    
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "截图服务",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "处理屏幕截图的服务"
            }
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
    }
    
    private fun createNotification(): Notification {
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("截图服务运行中")
            .setContentText("准备截图功能")
            .setSmallIcon(android.R.drawable.ic_menu_camera)
            .setOngoing(true)
            .build()
    }
    
    private fun startMediaProjection() {
        if (resultCode != Activity.RESULT_OK || resultData == null) {
            Log.e(TAG, "Invalid result for MediaProjection")
            return
        }
        
        try {
            val mediaProjectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
            mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, resultData!!)
            Log.d(TAG, "MediaProjection started successfully")
        } catch (e: Exception) {
            Log.e(TAG, "Error starting MediaProjection", e)
        }
    }
    
    private fun takeScreenshot() {
        if (mediaProjection == null) {
            Log.e(TAG, "MediaProjection is null")
            callback?.onScreenshotTaken(null)
            return
        }
        
        Log.d(TAG, "Starting screenshot process...")
        
        try {
            setupVirtualDisplay()
        } catch (e: Exception) {
            Log.e(TAG, "Error taking screenshot", e)
            callback?.onScreenshotTaken(null)
        }
    }
    
    private fun setupVirtualDisplay() {
        val displayMetrics = resources.displayMetrics
        val screenWidth = displayMetrics.widthPixels
        val screenHeight = displayMetrics.heightPixels
        val screenDensity = displayMetrics.densityDpi
        
        // 创建ImageReader
        imageReader = ImageReader.newInstance(screenWidth, screenHeight, PixelFormat.RGBA_8888, 2)
        
        // 设置监听器 - 延迟处理确保图像稳定
        imageReader?.setOnImageAvailableListener({ reader ->
            // 延迟一点时间确保虚拟显示稳定
            Handler(Looper.getMainLooper()).postDelayed({
                try {
                    val image = reader.acquireLatestImage()
                    if (image != null) {
                        Log.d(TAG, "Image captured: ${image.width}x${image.height}")
                        processImage(image)
                        image.close()
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "Error capturing image", e)
                    callback?.onScreenshotTaken(null)
                }
            }, 500) // 延迟500ms等待虚拟显示稳定
        }, Handler(Looper.getMainLooper()))
        
        // 创建虚拟显示
        virtualDisplay = mediaProjection?.createVirtualDisplay(
            "ScreenCapture",
            screenWidth,
            screenHeight,
            screenDensity,
            DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
            imageReader?.surface,
            null,
            null
        )
        
        Log.d(TAG, "Virtual display created: ${screenWidth}x${screenHeight}, density: $screenDensity")
    }
    
    private fun processImage(image: Image) {
        try {
            Log.d(TAG, "Processing image: ${image.width}x${image.height}, format: ${image.format}")
            
            val planes = image.planes
            if (planes.isEmpty()) {
                Log.e(TAG, "No image planes available")
                cleanup()
                callback?.onScreenshotTaken(null)
                return
            }
            
            val buffer = planes[0].buffer
            val pixelStride = planes[0].pixelStride
            val rowStride = planes[0].rowStride
            val rowPadding = rowStride - pixelStride * image.width
            
            Log.d(TAG, "Image details - pixelStride: $pixelStride, rowStride: $rowStride, rowPadding: $rowPadding")
            
            // 创建bitmap
            val bitmap = Bitmap.createBitmap(
                image.width + rowPadding / pixelStride,
                image.height,
                Bitmap.Config.ARGB_8888
            )
            bitmap.copyPixelsFromBuffer(buffer)
            
            // 裁剪到正确尺寸
            val croppedBitmap = Bitmap.createBitmap(bitmap, 0, 0, image.width, image.height)
            
            // 检查图像是否为黑屏
            if (isBitmapBlack(croppedBitmap)) {
                Log.w(TAG, "Screenshot appears to be black, this might be normal for the first few attempts")
            }
            
            // 保存到文件
            val screenshotPath = saveBitmapToFile(croppedBitmap)
            
            // 清理资源
            cleanup()
            
            // 回调结果
            callback?.onScreenshotTaken(screenshotPath)
            
        } catch (e: Exception) {
            Log.e(TAG, "Error processing image", e)
            cleanup()
            callback?.onScreenshotTaken(null)
        }
    }
    
    private fun isBitmapBlack(bitmap: Bitmap): Boolean {
        // 检查bitmap的几个像素点是否都是黑色
        val width = bitmap.width
        val height = bitmap.height
        val sampleSize = 10 // 检查10个像素点
        var blackPixels = 0
        
        for (i in 0 until sampleSize) {
            val x = (width * i / sampleSize).coerceAtMost(width - 1)
            val y = (height * i / sampleSize).coerceAtMost(height - 1)
            val pixel = bitmap.getPixel(x, y)
            if (pixel == android.graphics.Color.BLACK || pixel == 0) {
                blackPixels++
            }
        }
        
        return blackPixels > sampleSize * 0.8 // 如果80%以上的像素都是黑色，认为是黑屏
    }
    
    private fun saveBitmapToFile(bitmap: Bitmap): String? {
        return try {
            val screenshotsDir = File(cacheDir, "screenshots")
            if (!screenshotsDir.exists()) {
                screenshotsDir.mkdirs()
            }
            
            val timestamp = System.currentTimeMillis()
            val screenshotFile = File(screenshotsDir, "screenshot_$timestamp.png")
            
            FileOutputStream(screenshotFile).use { out ->
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
            }
            
            Log.d(TAG, "Screenshot saved: ${screenshotFile.absolutePath}")
            screenshotFile.absolutePath
            
        } catch (e: Exception) {
            Log.e(TAG, "Error saving screenshot", e)
            null
        }
    }
    
    private fun cleanup() {
        virtualDisplay?.release()
        virtualDisplay = null
        
        imageReader?.close()
        imageReader = null
    }
    
    private fun stopMediaProjection() {
        cleanup()
        mediaProjection?.stop()
        mediaProjection = null
    }
    
    override fun onDestroy() {
        stopMediaProjection()
        super.onDestroy()
    }
} 